/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ez2find.manager;

import com.ez2find.model.Area;
import com.ez2find.model.Gig;
import com.ez2find.model.GigCategorie;
import com.ez2find.model.RegisterUser;
import com.ez2find.model.Site;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Administrador
 */
@Stateless
public class GigManagerBean implements GigManagerLocal {
    
    @PersistenceContext
    private EntityManager em;
    
    public void create(Gig gig)throws Exception {
        em.persist(gig);
    }
 
    public void update(Gig gig)throws Exception {
        em.merge(gig);
    }
    
    public Gig merge(Gig gig)throws Exception {
        return em.merge(gig);
    }
    
    public void delete(Gig gig)throws Exception {
        gig=em.merge(gig);
        em.remove(gig);
    }
    
    public Gig find(long id){
        return em.find(Gig.class,id);
    }

    public List<Gig> listAll(){
        Query query=em.createNamedQuery("listAllGigs");
        List<Gig> result=query.getResultList();
        return result;
    }
    
    public long lastCode(){
        try{
            Query query=em.createNamedQuery("lastGigCode");
            return (Long) query.getSingleResult();
        }catch(Exception ex){
            return 0;
        }
    }
    
    public List<Gig> listGigsSite(Site site, boolean gigC, GigCategorie gigCategorie, String consult){
        Query query=em.createQuery("SELECT g FROM Gig g WHERE g.site=:site AND g.status='active'"+consult+" ORDER BY g.publishDate DESC, g.code DESC");
        query.setParameter("site", site);
        if(gigC)
            query.setParameter("gigCategorie", gigCategorie);
        List<Gig> result=query.getResultList();
        return result;
    }
    
    public List<Gig> listGigsArea(Area area, boolean gigC, GigCategorie gigCategorie, String consult){
        Query query=em.createQuery("SELECT g FROM Gig g WHERE g.area=:area AND g.status='active'"+consult+" ORDER BY g.publishDate DESC, g.code DESC");
        query.setParameter("area", area);
        if(gigC)
            query.setParameter("gigCategorie", gigCategorie);
        List<Gig> result=query.getResultList();
        return result;
    }
    
}
